//建议
var productSetting = {
    //请求url
    listUrl: "/tgProductSetting/list.action", //列表地址
    toAddUrl: "/tgProductSetting/toAdd.action", //去添加页面地址
    addUrl: "/tgProductSetting/add.action", //添加地址
    toEditUrl: "/tgProductSetting/toEdit.action?id=", //去修改页面地址
    editUrl: "/tgProductSetting/edit.action", //去修改页面地址
    deleteUrl: "/tgProductSetting/delete.action?id=", //删除页面地址
    toViewUrl: "/tgProductSetting/toView.action?id=", //详细页面地址
    getByIdUrl: "/tgProductSetting/getById.action", //根据id查询对象
    removeList: "/tgProductSetting/removeList.action", //根据id查询对象
    modifyDeleteStatusUrl: "/tgProductSetting/modifyDeleteStatus.action", //停用 或启用
    checkNameExitsUrl: "/tgProductSetting/checkNameExits.action", //检验唯一性,

    onlyName: $("#onlyName"), //修改，唯一验证时需要添加此属性
    m_title: $(".m_title"), //页面标题
    _title_val: "礼品",

    addform: jQuery("#addform"), //添加form
    queryfrom: jQuery("#queryForm"), //查询form
    addqueryfrom: jQuery("#addQueryForm"), //查询form
    addBtn: $("#addBtn"), //添加按钮
    queryBtn: $("#queryBtn"), //查询按钮
    addQueryBtn: $("#addQueryBtn"), //查询按钮
    left_menu_selected_id: $(".right").attr("data-name"), //左侧菜单选择id
 
    //属性

    id: $("#id"), //id
    giftType: $("#giftType"), //礼品分类（求职者去面试、开发者礼品等）
    productId: $("#productId"), //商品id
    quantity: $("#quantity"), //商品数量
    remark: $("#remark"), //礼品备注
    inTime: $("#inTime"), //录入时间
    inPerson: $("#inPerson"), //录入人
    updateTime: $("#updateTime"), //更新时间
    updatePerson: $("#updatePerson"), //更新人
    inPersonName: $("#inPersonName"),
    //页面初始化
    initPage: function() {
        var self = this;
        self.currPage = common.getCurrPageFlag();
        common.initLeftMenuSelected(self.left_menu_selected_id);

        //初始化标题
        common.initPageTitle(self._title_val, self.m_title);
        //列表页面
        if (self.currPage != "list") {
            self.addform.validationEngine({ scroll: false });
            self.addBtn.unbind("click").click(function() {
                self.add();
            });
        }
        if (self.currPage == "list") {
            self.initSeletePage();
        } else
        if (self.currPage == "edit") {
            self.initEditPage();
        } else
        if (self.currPage == "add") {
            self.initAddPage();
        } else
        if (self.currPage == "detail") {
            self.initDetailPage();
        }
    },
    initSeletePage: function() {
        var self = this;
        self.queryfrom.validationEngine({ scroll: false });
        self.queryBtn.unbind("click").click(function() {
            self.query();
        });
    },
    //列表查询
    query: function() {
        var self = this;
        var b = self.queryfrom.validationEngine('validate');
        if (!b) {
            return false;
        }
        var serializeObj = common.serializeJson("queryForm");
        var jsonStr = JSON.stringify(serializeObj)
        location.href = this.listUrl + "?jsonParam=" + jsonStr;
    },
    //添加列表查询
    addQuery: function() {
        var self = this;
        var b = self.addqueryfrom.validationEngine('validate');
        if (!b) {
            return false;
        }
        var serializeObj = common.serializeJson("addQueryForm");
        var jsonStr = JSON.stringify(serializeObj)
        location.href = this.toAddUrl + "?jsonParam=" + jsonStr;
    },
    //跳转列表页面
    tolist: function() {
        location.href = this.listUrl;
    },
    //跳转到添加页面
    toAdd: function(id) {
        location.href = this.toAddUrl + "?id=" + id;
    },
    //跳转修改页面
    toEdit: function(id) {
        location.href = this.toEditUrl + id;
    },
    //跳转详情页面
    toDetail: function(id) {
        location.href = this.toViewUrl + id;
    },
    //初始化添加页面
    initAddPage: function() {
        var self = this;
        self.addform.attr("action", self.addUrl);
        
        self.addqueryfrom.validationEngine({ scroll: false });
        self.addQueryBtn.unbind("click").click(function() {
            self.addQuery();
        });
        self.initSelectBox();
        var search = location.search;
        console.log(search);
        if (search.indexOf("?") != -1 && search.indexOf("=") != -1) {    //判断是否有参数
        	var eqIndex = search.indexOf("=") + 1;
        	var nextIndex = search.indexOf("&");
        	var idStr;
        	if(nextIndex > eqIndex)
        		idStr = search.substring(eqIndex, nextIndex);
        	else
        		idStr = search.substr(eqIndex);
            console.log(idStr);
            self.productSettingEdit(idStr);
         }
    },
    //初始化详情页面数据
    initDetailPage: function() {
        var self = this;
        self.getById(self.id.val(), function(result) {
            if (result.s > 0) {
                self.setForm(result.data);
                $("input").attr("disabled", true);
                self.addBtn.hide();
                $("._detail").show();
            } //不存在
            else if (result.s == -1000) {
                location.href = common.notFindUrl;
            } else {
                common.alert(result.d);
            }
        });
    },

    //建议 添加 
    add: function() {
        var self = this;
        var b = self.addform.validationEngine('validate');
        if (!b) {
            return false;
        }
        //$("#desc").val(CKEDITOR.instances.desc1.getData());
        //$("#moreDesc").val(CKEDITOR.instances.desc2.getData());
        if (self.currPage == "edit") {
            common.openModal("delete_sure", "确定修改信息吗？");
            $("#delete_sure_a").unbind("click").click(function() {
                self.ajaxSubmitForm();
            });
        } else {
            self.ajaxSubmitForm();
        }
    },
    //提交表单
    ajaxSubmitForm: function() {
        var self = this;
        self.addform.ajaxSubmit(function(resp) {
            if (resp.s > 0) {
                location.href = self.listUrl;
            } else {
                //唯一判断
                if (resp.s == -100) {
                    $("#name").validationEngine("showPrompt", resp.d, "error");
                }
            }
        });
    },
    //初始化修改页面数据
    initEditPage: function() {
        var self = this;
        self.getById(this.id.val(), function(result) {
            if (result.s > 0) {
                self.setForm(result.data);
            } //不存在
            else if (result.s == -1000) {
                location.href = common.notFindUrl;
            } else {
                common.alert(resp.d);
            }
        });
        self.addform.attr("action", self.editUrl);
    },
    //初始化选择框事件绑定
    initSelectBox: function() {
        var self = this;
    	$(".select-all").on("click", function(event){
    		var $this = $(this);
    		var isSelect = $this.is(':checked');
    		$this.closest("table").find("input[type='checkbox']").each(function(i, value){
    			$(this).attr('checked', isSelect);
    		});
    	});
    	$(".conform-select-submit").on("click", function(event){
    		var ids = new Array();
    		var $this = $(this);
    		$this.closest(".form").find(".select").each(function(i, value){
    			var id = $(this).attr('data-id');
        		console.log(id);
    			if($(this).attr('checked') && id && id.length > 0) ids.push(id);
    		});
    		$.ajax({
                type: "POST",
    			contentType : 'application/json', 
                url: "/tgProductSetting/addList.action",
                dataType:"json",
                data: JSON.stringify(ids), // 
                error: function(){
                	alert("出错了，请重试");
                },
                success: function(result){
                	 location.reload();
                }
            });
    		return false;
    	});
    	$(".cancel-select-submit").on("click", function(event){
    		var ids = new Array();
    		var $this = $(this);
    		$this.closest(".form").find(".select").each(function(i, value){
    			var id = $(this).attr('data-id');
        		console.log(id);
    			if($(this).attr('checked') && id && id.length > 0) ids.push(id);
    		});
    		$.ajax({
                type: "POST",
    			contentType : 'application/json', 
                url: "/tgProductSetting/removeList.action",
                dataType:"json",
                data: JSON.stringify(ids), // 
                error: function(){
                	alert("出错了，请重试");
                },
                success: function(result){
                	 location.reload();
                }
            });
    		return false;
    	});
    	$(".productSetting .edit").on("click", function(event){
    		var $this = $(this);
    		if($this.hasClass("flag")){
    			self.productSettingSave($this.attr("data-id"));
    		}else{
    			self.productSettingEdit($this.attr("data-id"));
    		}
    		return false;
    	});
    },
    productSettingEdit: function(id){
    	var $node = $(".productSetting").find("tr[data-id="+id+"]");
    	$node.find(".quantity input").attr("readonly", false);
    	$node.find(".quantity input").focus();
    	$node.find(".remark input").attr("readonly", false);
    	$node.find(".edit").addClass("flag");
    	$node.find(".edit").text("保存");
    },
    productSettingSave: function(id){
    	console.log(id);
    	var $node = $(".productSetting").find("tr[data-id="+id+"]");
    	if(!$node) return false;
    	var giftType = $node.find("#gift_type option:selected").val();
    	var quantity = $node.find(".quantity input").val();
    	var remark = $node.find(".remark input").val();
    	
    	$.ajax({
            type: "POST",
			contentType : 'application/json', 
            url: "/tgProductSetting/edit.action",
            dataType:"json",
            data: JSON.stringify({id:id, giftType:giftType, quantity:quantity, remark:remark}), // 
            error: function(){
            	alert("出错了，请重试");
            },
            success: function(result){
            	$node.find(".quantity input").attr("readonly", true);
            	$node.find(".remark input").attr("readonly", true);
            	$node.find(".edit").removeClass("flag");
            	$node.find(".edit").text("修改");
            }
        });
    	return false;
    },
    //根据id查询信息
    getById: function(id, callBack) {
        var self = this;
        var obj = null;
        var rData = { "id": id };
        $.ajax({
            url: self.getByIdUrl,
            data: rData, // 
            success: callBack
        });
    },
    //删除
    toDelete: function(id) {
        var self = this;
        common.openModal("delete_sure", "确定删除吗？");
        $("#delete_sure_a").unbind("click").click(function() {
            location.href = self.deleteUrl + id;
        });
    },
    //更新删除状态
    modifyDeleteStatus: function(id, status) {
        var self = this;
        var delTitle = "";
        if (status == 1) {
            status = 2;
            delTitle = "确定暂停吗?";
        } else
        if (status == 2) {
            status = 1;
            delTitle = "确定启用吗？";
        }
        common.openModal("delete_sure", delTitle);
        $("#delete_sure_a").unbind("click").click(function() {
            location.href = self.modifyDeleteStatusUrl + "?id=" + id + "&deleteStatus=" + status;
        });
    },
    //填充表单数据
    setForm: function(obj) {
        var self = this;
        //唯一验证时需要记录原来的名称
        self.onlyName.val(obj.name);
        //赋值
        self.id.val(obj.id); //id

        //用户详情显示信息
        $("input[name='giftType'][value='" + obj.giftType + "']").attr("checked", true); //礼品分类（求职者去面试、开发者礼品等）
        $("input[name='productId'][value='" + obj.productId + "']").attr("checked", true); //商品id
        $("input[name='quantity'][value='" + obj.quantity + "']").attr("checked", true); //商品数量
        self.remark.val(obj.remark); //礼品备注
        if (obj.inTime && obj.inTime > 0) {
            var new1 = new Date(obj.inTime).format("yyyy-MM-dd HH:mm");
            self.inTime.html(new1); //录入时间
        }

        //其它属性
        self.inPerson.html(obj.inPerson);

        //其它属性
        if (obj.updateTime && obj.updateTime > 0) {
            var new1 = new Date(obj.updateTime).format("yyyy-MM");
            self.updateTime.val(new1); //更新时间
        }
        $("input[name='updatePerson'][value='" + obj.updatePerson + "']").attr("checked", true); //更新人
        self.inPersonName.html(obj.inPersonName);
    },
    //检查名称唯一性
    checkNameExits: function(param, callBack) {
        var self = this;
        $.ajax({
            url: self.checkNameExitsUrl,
            data: param, // 
            success: callBack
        });
    },
    //检查名称，回调
    checkNameExitCallBack: function(result) {
        if (result.s < 0) {
            common.alert(result.d, 2000);
        }
    }
}
